struct Solution {}

fn main() {}

// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
  pub val: i32,
  pub left: Option<Rc<RefCell<TreeNode>>>,
  pub right: Option<Rc<RefCell<TreeNode>>>,
}

impl TreeNode {
  #[inline]
  pub fn new(val: i32) -> Self {
    TreeNode {
      val,
      left: None,
      right: None
    }
  }
}

use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
    pub fn is_unival_tree(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
        let mut ans = true;
        let mut val = root.clone().unwrap().borrow().val;
        Self::do_preorder(root, &mut ans, val);
        ans
    }

    fn do_preorder(root: Option<Rc<RefCell<TreeNode>>>, ans: &mut bool, val: i32) {
        if !*ans {
            return;
        }
        if root.is_none() {
            return;
        }
        let node = root.unwrap();
        if val != node.borrow().val {
            *ans = false;
            return;
        }
        Self::do_preorder(node.borrow().left.clone(), ans, node.borrow().val);
        Self::do_preorder(node.borrow().right.clone(), ans, node.borrow().val);
    }
}